package cn.android.mydata2.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import java.util.Date;
import java.util.List;

import cn.android.mydata2.receiver.AlarmReceiver;
import cn.android.mydata2.utils.TrafficUtils;

public class HorizonService extends Service {
    public HorizonService() {
    }

    @Override
    public IBinder onBind(Intent intent) {

        return  null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PackageManager pm = getPackageManager();
                List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
                for (ApplicationInfo packageInfo : packages) {
                    //Log.e("TAG","UID = "+packageInfo.uid);
                    if (packageInfo.packageName.contains("com.android") || packageInfo.loadLabel(getPackageManager()).toString().contains("com")) {
                        continue;
                    }

                    //

                    TrafficUtils.fetchOneAppData(packageInfo.uid, getApplicationContext());

                    //Log.e("TAG","App name:"+packageInfo.loadLabel(getPackageManager()).toString());
                }
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int five = 1000 * 100; // 这是5s
        long triggerAtTime = SystemClock.elapsedRealtime() + five;
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }
}
